package com.icode.chat.websocket;

import com.icode.chat.Chat;
import com.icode.chat.ChatRoom;
import com.icode.chat.ChatRoomsSingleton;
import com.icode.chat.message.ChatMessage;
import com.icode.chat.message.Message;
import com.icode.chat.message.SystemMessage;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Queue;

/**
 * User: alexz
 * Date: 14-7-31
 * Time: 下午5:20
 */
@ServerEndpoint(value = "/chat/{topic}")
public class ChatEndpoint {
    private Session session;

    @OnOpen
    public void open(Session session, @PathParam("topic") String topic) throws IOException {
        this.session = session;

        ChatRoom chatRoom = ChatRoomsSingleton.singleton().get(topic.toUpperCase());
        List<String> values = session.getRequestParameterMap().get("chatName");
        String chatName = values == null ? "游客【" + session.hashCode() + "】" : values.get(0);
        Chat chat = new Chat(chatName, session);
        chatRoom.put(session.hashCode(), chat);

        Queue<Message> latestMessages = chatRoom.getLatestMessages();
        for (Message latestMessage : latestMessages) {
            chatRoom.push(session, latestMessage);
        }

        chatRoom.push(new SystemMessage(chat.getName() + "进入了聊天室"));

        chatRoom.pushOnlineUsers();
    }

    @OnClose
    public void close(Session session, @PathParam("topic") String topic) throws IOException {
        ChatRoom chatRoom = ChatRoomsSingleton.singleton().get(topic.toUpperCase());
        int sessionId = session.hashCode();
        Chat chat = chatRoom.get(sessionId);
        chatRoom.remove(sessionId);

        chatRoom.push(new SystemMessage(chat.getName() + "退出了聊天室"));

        chatRoom.pushOnlineUsers();
    }

    @OnMessage
    public void receive(String message, @PathParam("topic") String topic) throws IOException {
        ChatRoom chatRoom = ChatRoomsSingleton.singleton().get(topic.toUpperCase());
        Integer sessionId = session.hashCode();
        Chat chat = chatRoom.get(sessionId);
        chatRoom.push(new ChatMessage(chat.getName(), message));
    }

    @OnError
    public void error(Throwable t) throws Throwable {
    }
}
